package com.tenton.netty.unicast.server;

import com.tenton.netty.pool.ThreadPool;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName： UnicastServerHandler
 * @Description： 单播服务端
 * @Author： tangdong
 * @Date： 2024/7/4 09:41
 */
@Component
@Slf4j
public class UnicastServerService implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        ThreadPool.dataDealThreadPool.execute(() -> {
            start();
        });
        log.info("Udp单播发送端启动成功，绑定接收IP：{},端口为：{}", "192.168.4.169", 8888);
    }

    private void start() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    protected void initChannel(NioDatagramChannel channel) throws Exception {
                        channel.pipeline().addLast(new UnicastServerHandler());
                    }
                });
        try {
            Channel channel = bootstrap.bind(8000).sync().channel();
            InetSocketAddress address = new InetSocketAddress("192.168.4.169", 8888);
            for (int i = 0; i < 5; i++) {
                TimeUnit.SECONDS.sleep(1);
                String msg = "send " + i;
                ByteBuf byteBuf = new UnpooledByteBufAllocator(false).buffer();
                byteBuf.writeCharSequence(msg, StandardCharsets.UTF_8);
                DatagramPacket packet = new DatagramPacket(byteBuf, address);
                channel.writeAndFlush(packet);
            }
            channel.closeFuture().sync();
            group.shutdownGracefully();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
